import * as Cesium from 'cesium'
import { debounce } from 'lodash'
import { getSingleClass } from '../../../utils/unsorted.js'

export class DebouncedCesiumMouseMove {
    constructor(viewer = window.cesiumViewer, wait = 0) {
        this.viewer = viewer
        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
        this.debounceCallback = debounce(this.callback, wait)
        this.callbackArray = []
        this.bind()
    }
    addCallback(func) {
        this.callbackArray.push(func)
    }

    callback({ endPosition }) {
        const pickedObject = this.viewer.scene.pick(endPosition)
        this.callbackArray.forEach((callback) => {
            callback(pickedObject)
        })
    }

    bind() {
        this.handler.setInputAction((movement) => {
            this.debounceCallback(movement)
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }
    destroy() {
        this.handler.destroy()
        this.debounceCallback.cancel()
        this.callbackArray.length = 0
    }
}

export const SingleDebouncedCesiumMouseMove = getSingleClass(
    DebouncedCesiumMouseMove
)
